<template>
  <van-card
      v-for="team in teamList"
      :key="team.id"
      :desc="team.description"
      :title="team.teamName"
  >
    <template #tags>
      <van-tag type="primary" size="large">最多：{{ team.maxNum }}人</van-tag>
    </template>
    <template #footer>
      <van-button v-if="team.isJoin" type="danger" size="mini" @click="exitGroup(team)">退出</van-button>
      <van-button v-else type="primary" size="mini" @click="joinGroup(team)">加入</van-button>
      <van-button size="mini" @click="toDetail(team)">详情</van-button>
    </template>
  </van-card>
</template>

<script setup>
import {onMounted, reactive} from 'vue';
import {exitTeamApi, joinTeamApi, selectUserTeam, teamListApi} from "../apis/teamApi.js";
import {ref} from "vue";
import router from "../router/index.js";
import {useUserStore} from "../store/userStore.js";
import {showToast} from "vant";

const teamList = reactive([]); // 所有队伍信息
const userTeamList = ref([]); // 当前用户加入的队伍关系

const userStore = useUserStore()


// 获取队伍列表
onMounted(async () => {
  const resp = await teamListApi();
  teamList.push(...resp.data.data);

  // 获取当前用户所加入的所有队伍信息，判断按钮颜色
  const resp1 = await selectUserTeam();
  userTeamList.value = resp1.data.data;

  console.log("队伍列表", teamList);
  console.log("关系列表", userTeamList.value);

  // 将两个列表通过关系转换成一个新的列表
  transform(teamList, userTeamList);

  console.log("合并结果：", teamList);
});

// 将两个列表通过关系转换成一个新的列表.加入的队伍为true，未加入的队伍为false
function transform(teamList, userTeamList) {
  // 先找到已经加入的队伍提取出来
  const tempTeamList = teamList.filter(item => {
    return userTeamList.value.some(userTeam => item.id === userTeam.teamId);
  }).map(item => {
    return {
      ...item,
      isJoin: true
    };
  });

  // 再找到未加入的队伍提取出来（通过去重查找）
  const tempTeamList2 = teamList.filter(item => {
    return !tempTeamList.some(team => team.id === item.id);
  }).map(item => {
    return {
      ...item,
      isJoin: false
    };
  });

  // 清空原数组并重新赋值（不能直接赋值为了不破坏响应式对象的响应性）
  teamList.splice(0, teamList.length, ...tempTeamList.concat(tempTeamList2));
}

// 加入团队
async function joinGroup(team) {
  try {
    // 调用后端 API 加入团队
    console.log(team.teamName);
    const resp = await joinTeamApi(team.teamName);
    console.log(resp);
    if (resp.data.code === 200) {
      // 更新团队的 isJoin 状态
      team.isJoin = true;
      console.log(`加入团队 ${team.teamName} 成功`);
    } else {
      console.error(`加入团队 ${team.teamName} 失败：`, resp.data.message);
    }
  } catch (error) {
    console.error(`加入团队 ${team.teamName} 失败：`, error);
  }
}

// 退出团队
async function exitGroup(team) {


  //先验证当前登录用户是不是队长

  const userId = userStore.userInfo.id
  if (userId === team.userId) {
    showDialog({
      message: '队长无法退出队伍，请进入详情页面解散队伍',
    }).then(() => {
      // on close
      showToast("退出失败")
    });
    return
  }


  try {
    // 调用后端 API 退出团队
    const resp = await exitTeamApi(team.teamName);
    console.log(resp);
    if (resp.data.code === 200) {
      // 更新团队的 isJoin 状态
      team.isJoin = false;
      console.log(`退出团队 ${team.teamName} 成功`);
    } else {
      console.error(`退出团队 ${team.teamName} 失败：`, resp.data.message);
    }
  } catch (error) {
    console.error(`退出团队 ${team.teamName} 失败：`, error);
  }
}


function toDetail(team) {
  router.push({
    path: '/teamDetail',
    query: {
      teamId: team.id,
      teamName: team.teamName,
      maxNum: team.maxNum,
      description: team.description,
      leaderId: team.userId,  // 队长的用户 ID
      expireTime: team.expireTime
    }
  })
}
</script>


<style scoped>

</style>